var tableLangues = [];
tableLangues['fr'] = 'français';
tableLangues['en'] = 'anglais';
tableLangues['de'] = 'allemand';
tableLangues['es'] = 'espagnol';


$(document).ready(function(){
    if(typeof $('.table_sortable') !== 'undefined' && $('.table_sortable').length > 0 ){
        $('.table_sortable').dataTable({
            "bPaginate": true,
            "bLengthChange": true,
            "bFilter": false,
            "bSort": true,
            "bInfo": true,
            "bAutoWidth": true,
            "oLanguage": {
                "sProcessing":"Traitement en cours...",
                "sLengthMenu":"Afficher _MENU_ éléments",
                "sZeroRecords":"Aucun élément à afficher",
                "sInfo":"Affichage de l'élement _START_ à _END_ sur _TOTAL_ éléments",
                "sInfoEmpty":"Affichage de l'élement 0 à 0 sur 0 éléments",
                "sInfoFiltered":"(filtré de _MAX_ éléments au total)",
                "sInfoPostFix":"",
                "sSearch":"Rechercher:",
                "sUrl":"",
                "oPaginate":{
                    "sFirst":"Premier",
                    "sPrevious":"Précédent",
                    "sNext":"Suivant",
                    "sLast":"Dernier"
                }
            },
            "aoColumnDefs": [
                { 'bSortable': false, 'aTargets': [ 0 ] },
                { 'bSortable': false, 'aTargets': [ -1 ] }
            ]
        });
    }
        
    /* bouton forumaires */
    $('.pwe-ui-btn').button();
    /* menu sidebar*/
    $('.pwe-ui-menu').menu();
    
    /* editeur menus */
    $('#tabs-menu').tabs();
    /* editeur items menu */
    $('.liste-items-menu').sortable({
        update:function(evt,ui){
            var liste = ui.item.parent().find('.orderValueCell'); 
            if(liste.length>0){
                var newOrder = 0;
                $.each(liste,function(){
                    $(this).find('span.value').html(newOrder+1);
                    $(this).find('input.orderValue').attr('value',newOrder);
                    newOrder++;
                });
            }else{
                var liste = ui.item.parent().find('input.orderValue'); 
                var newOrder = 0;
                $.each(liste,function(){
                    $(this).attr('value',newOrder);
                    newOrder++;
                });
            }
            /**/
        }
    });
    //$('.liste-items-menu').disableSelection();
    
    /* base de données */
    $('.checkBdd').change(function(){
        checkDataBase();
    });
    
    $('.pwe-ui-btn').button();    
    $( ".dates" ).datepicker({
        changeMonth: true,
        changeYear: true,
        dateFormat: "yy-mm-dd"
    });
    
    $( ".dates" ).datepicker( "option", "regional", "fr" );
    
    $( ".datePublication" ).datetimepicker({
        changeMonth: true,
        changeYear: true,
        showTime: true,
        closeText: "OK",
        currentText: "maintenant",
        separator: ' ',
        dateFormat: "yy-mm-dd",
        timeFormat: "hh:mm:ss",
        hourText: "heure",
        minuteText: "minute",
        secondText: "seconde"
    });
    $( ".dateNaissance" ).datepicker({
        changeMonth: true,
        changeYear: true,
        closeText: "OK",
        currentText: "maintenant",
        separator: ' ',
        dateFormat: "yy-mm-dd"
    });

    /* editeur de contenu */
    if(typeof CKEDITOR !== 'undefined'){
        CKEDITOR.replaceAll( 'editor', {
            customConfig: './config.js'
        });
    }
    $('.accordionListeContent').accordion();
    $('#findPermalien').dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        height:500,
        width: 450
    });
    $('#targetSidebar').dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        height:500,
        width: 450
    });
    $('#dialogBox').dialog({
        autoOpen: false,
        modal: true,
        resizable: false,
        position: ['middle',28],
        create: function (event) { $(event.target).parent().css('position', 'fixed');}
    });

    initConfirmAction();
});

var checkDataBase = function(){
    var datas = {
        server:$('#bdd_server').val(),
        username:$('#bdd_username').val(),
        password:$('#bdd_password').val(),
        database_name:$('#bdd_database_name').val(),
        database_prefix:$('#bdd_database_prefix').val()
    };

    doAjax('../checkDataBase.ajax',datas,function(data){
        $('#error_serveur').html('');
        if(data['server_connexion']['success']){
            if(data['database_connexion']['success']){
                if(data['table_connexion']['success']){
                    $("#save_bdd").hide();
                    $("#bdd_ok").show();
                }else{
                    $("#save_bdd").show(); // installation des tables
                    $("#bdd_ok").hide();
                }
            }else{
                $("#save_bdd").hide();
                $("#bdd_ok").hide();
                $('#error_serveur').html("La base de données n'existe pas !");
            }
        }else{
            $("#save_bdd").hide();
            $("#bdd_ok").hide();
            $('#error_serveur').html('connexion au serveur impossible !');
        }
    },'no-error','#error');
};

var initConfirmAction = function(){
    $('.confirmAction').unbind('click');
    $('.confirmAction').click(function(){
        var answer = confirm('êtes vous sûr de vouloir effectuer cette opération ?'+"\n\n"+$(this).attr('title'));
        if(answer){
            answer = false;
            return true;
        }else{
            return false;
        }
        
    });
};

var toggleAddItem = function(targetStr){
   var target = $('#'+targetStr);
   if(target.css('display')!=='none') target.hide();
   else target.show();
};

var generatePermalien = function(texte){
    var permalien = $('#permalien');
    if(permalien.val() === ''){
        permalien.val(urlize(texte));
    }
};
var validPermalien = function(texte){
    var permalien = $('#permalien');
    permalien.val(urlize(texte));
};

var urlize = function(str){
    str = str.replace(/^\s+|\s+$/g, ''); // trim
    str = str.toLowerCase();

    // remove accents, swap ñ for n, etc
    var from = "ãàáäâẽèéëêìíïîõòóöôùúüûñç·/_,:;";
    var to   = "aaaaaeeeeeiiiiooooouuuunc------";
    for (var i=0,l=from.length;i<l;i++){
      str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
    }

    str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
      .replace(/\s+/g, '-') // collapse whitespace and replace by -
      .replace(/-+/g, '-'); // collapse dashes

    return str;
};

var openDialog = function(dialogId,returnTargetId){
    $('#'+dialogId).dialog('open');
    $('#'+dialogId + ' #'+dialogId+'ReturnTarget').val(returnTargetId);
};
var getPermalienFromListe = function(item,dialogId){
    var permalien = item.attr('permalien');
    var modele = item.attr('modele');
    var modele_id = item.attr('modele_id');
    if(dialogId==='targetSidebar') permalien = 'sidebar-'+permalien;
    $('#'+$('#'+dialogId + ' #'+dialogId+'ReturnTarget').val()).val(permalien);
    $('#'+$('#'+dialogId + ' #'+dialogId+'ReturnTarget').val()+'_modele').val(modele);
    $('#'+$('#'+dialogId + ' #'+dialogId+'ReturnTarget').val()+'_modele_id').val(modele_id);
    $('#'+dialogId).dialog('close');
};

// edition des users
var openAddUser = function(){
    $('#dialogBox').dialog('option','title','Ajouter un utilisateur');
    $('#dialogBox').dialog('option','width',450);
    $('#dialogBox').dialog('option','height',345);
    $('#dialogBox iframe').attr('src','tools/editUser.php');
    $('#dialogBox').dialog('open');
};
var openUpdateUser = function(modeleId){
    $('#dialogBox').dialog('option','title','Modifier un utilisateur');
    $('#dialogBox').dialog('option','width',450);
    $('#dialogBox').dialog('option','height',345);
    $('#dialogBox iframe').attr('src','tools/editUser.php?modele_id='+modeleId);
    $('#dialogBox').dialog('open');
};
var removeUser = function(modeleId){
    $('#dialogBox').dialog('option','title','supprimer un utilisateur');
    $('#dialogBox').dialog('option','width',450);
    $('#dialogBox').dialog('option','height',305);
    $('#dialogBox iframe').attr('src','tools/editUser.php?action=delete&modele_id='+modeleId);
    $('#dialogBox').dialog('open');
};

// edition des medias de galerie
var openAddMedia = function(modeleId,modele,maxWidth,maxHeight,module,forceTitle,sousDossier){
    if(typeof maxWidth === 'undefined') maxWidth = 0;
    if(typeof maxHeight === 'undefined') maxHeight = 0;
    if(typeof module === 'undefined') module = '';
    if(typeof forceTitle === 'undefined') forceTitle = '';
    if(typeof sousDossier === 'undefined') sousDossier = '';
    $('#dialogBox').dialog('option','title','Ajouter un média');
    $('#dialogBox').dialog('option','width','85%');
    $('#dialogBox').dialog('option','height',($(window).height()-40));
    $('#dialogBox iframe').attr('src','tools/editMedia.php?modele='+modele+'&module='+module+'&modele_id='+modeleId+'&max_width='+maxWidth+'&max_height='+maxHeight+'&force_title='+forceTitle+'&sous_dossier='+sousDossier);
    $('#dialogBox').dialog('open');
};
var openUpdateMedia = function(modeleId,mediaId,modele,maxWidth,maxHeight,module,forceTitle,sousDossier){
    if(typeof maxWidth === 'undefined') maxWidth = 0;
    if(typeof maxHeight === 'undefined') maxHeight = 0;
    if(typeof module === 'undefined') module = '';
    if(typeof forceTitle === 'undefined') forceTitle = '';
    if(typeof sousDossier === 'undefined') sousDossier = '';
    $('#dialogBox').dialog('option','title','Modifier un média');
    $('#dialogBox').dialog('option','width','85%');
    $('#dialogBox').dialog('option','height',($(window).height()-40));
    $('#dialogBox iframe').attr('src','tools/editMedia.php?modele='+modele+'&module='+module+'&modele_id='+modeleId+'&media_id='+mediaId+'&max_width='+maxWidth+'&max_height='+maxHeight+'&force_title='+forceTitle+'&sous_dossier='+sousDossier);
    $('#dialogBox').dialog('open');
};
var openSelectMedia = function(modeleId,modele,module){
    if(typeof module === 'undefined') module = '';
    $('#dialogBox').dialog('option','title','Selectionner un média');
    $('#dialogBox').dialog('option','width',720);
    $('#dialogBox').dialog('option','height',576);
    $('#dialogBox iframe').attr('src','tools/selectMedia.php?modele='+modele+'&modele_id='+modeleId+'&module='+module);
    $('#dialogBox').dialog('open');
};
var addMedia = function(mediaDatas){
    if(mediaDatas.modele!==''&&mediaDatas.modele!=='galerie'){
        $('#mediaPublication').html('<img src="'+mediaDatas.path+'" title="'+mediaDatas.title+'" class="media_modele" />');
        var htmlAction  = '<a href="javascript:removeMedia('+mediaDatas.modele_id+','+mediaDatas.media_id+',\''+mediaDatas.modele+'\','+mediaDatas.maxWidth+','+mediaDatas.maxHeight+',\''+mediaDatas.module+'\');" class="confirmAction pwe-ui-btn" title="Supprimer le media \''+mediaDatas.title+'\'">Supprimer</a>\n\
<a class="pwe-ui-btn" href="javascript:openUpdateMedia('+mediaDatas.modele_id+','+mediaDatas.media_id+',\''+mediaDatas.modele+'\','+mediaDatas.maxWidth+','+mediaDatas.maxHeight+',\''+mediaDatas.module+'\');">modifier</a>';
        $('#mediaAction').html(htmlAction);
        if(mediaDatas.modele==='logo'){
            $('#logo_media_id').val(mediaDatas.media_id);
        }
        initConfirmAction();
        $('.pwe-ui-btn').button();
        closeDialogBox();
    }else{
        closeDialogBox(true);
    }
};

var updateMedia = function(mediaDatas){
    if(mediaDatas.modele!==''&&mediaDatas.modele!=='galerie'){
        $('#mediaPublication').html('<img src="'+mediaDatas.path+'" title="'+mediaDatas.title+'" class="media_modele" />');
        var htmlAction  = '<a href="javascript:removeMedia('+mediaDatas.modele_id+','+mediaDatas.media_id+',\''+mediaDatas.modele+'\','+mediaDatas.maxWidth+','+mediaDatas.maxHeight+',\''+mediaDatas.module+'\');" class="confirmAction pwe-ui-btn" title="Supprimer le media \''+mediaDatas.title+'\'">Supprimer</a>\n\
<a class="pwe-ui-btn" href="javascript:openUpdateMedia('+mediaDatas.modele_id+','+mediaDatas.media_id+',\''+mediaDatas.modele+'\','+mediaDatas.maxWidth+','+mediaDatas.maxHeight+',\''+mediaDatas.module+'\');">modifier</a>';
        $('#mediaAction').html(htmlAction);
        if(mediaDatas.modele==='logo'){
            $('#logo_media_id').val(mediaDatas.media_id);
        }
        initConfirmAction();
        $('.pwe-ui-btn').button();
        closeDialogBox();
    }else{
        closeDialogBox(true);
    }
};
var removeMedia = function(modeleId,mediaId,modele,maxWidth,maxHeight,module){
    if(typeof maxWidth === 'undefined') maxWidth = 0;
    if(typeof maxHeight === 'undefined') maxHeight = 0;
    if(typeof module === 'undefined') module = '';
    $('#dialogBox iframe').attr('src','tools/editMedia.php?suppr=1&modele='+modele+'&module='+module+'&modele_id='+modeleId+'&media_id='+mediaId);
    $('#dialogBox').dialog('open');
    if(modele!==''&&modele!=='galerie'){
        $('#mediaPublication').html('');
        var htmlAction  = '<a class="pwe-ui-btn" href="javascript:openAddMedia('+modeleId+',\''+modele+'\','+maxWidth+','+maxHeight+',\''+module+'\');">définir</a>';
        $('#mediaAction').html(htmlAction);
        if(modele==='logo'){
            $('#logo_media_id').val(0);
        }
        $('.pwe-ui-btn').button();
    }
};

/* redirections */
var openAddRedirection = function(modele_id,modele){
    $('#dialogBox').dialog('option','title','Ajouter une redirection');
    $('#dialogBox').dialog('option','width',450);
    $('#dialogBox').dialog('option','height',305);
    $('#dialogBox iframe').attr('src','tools/editRedirection.php?action=create&modele_id='+modele_id+'&modele='+modele);
    $('#dialogBox').dialog('open');
};
var addRedirection = function(redirectionDatas){
    var nbLigne = $('#liste_redirection tbody tr').length;
    var html = '<tr id="redirection_'+nbLigne+'" >\n\
    <td class="lien-redirection">'+redirectionDatas.lien+'</td>\n\
    <td class="code-redirection">'+redirectionDatas.code+'</td>\n\
    <td class="action-redirection" align="right"><a class="pwe-ui-btn confirmAction right" title="Supprimer cette redirection" href="javascript:openRemoveRedirection('+nbLigne+',\''+redirectionDatas.lien+'\');">supprimer</a> <a class="pwe-ui-btn right" href="javascript:openUpdateRedirection('+nbLigne+',\''+redirectionDatas.lien+'\');">modifier</a></td>\n\
    ';
    $('#liste_redirection tbody').append(html);
    $('.pwe-ui-btn').button();
    closeDialogBox();
    initConfirmAction();
};
var openRemoveRedirection = function(numLigne,lien){
    $('#dialogBox').dialog('option','title','Ajouter une redirection');
    $('#dialogBox').dialog('option','width',450);
    $('#dialogBox').dialog('option','height',305);
    $('#dialogBox iframe').attr('src','tools/editRedirection.php?action=delete&ligne_id='+numLigne+'&lien='+lien);
    $('#dialogBox').dialog('open');
};
var removeRedirection = function(redirectionDatas){
    closeDialogBox();
    $('#liste_redirection tbody #redirection_'+redirectionDatas.ligne_id).remove();
};
var openUpdateRedirection = function(numLigne,lien){
    $('#dialogBox').dialog('option','title','Ajouter une redirection');
    $('#dialogBox').dialog('option','width',450);
    $('#dialogBox').dialog('option','height',305);
    $('#dialogBox iframe').attr('src','tools/editRedirection.php?action=update&ligne_id='+numLigne+'&lien='+lien);
    $('#dialogBox').dialog('open');
};
var updateRedirection = function(redirectionDatas){
    $('#liste_redirection tbody #redirection_'+redirectionDatas.ligne_id+' td.lien-redirection').html(redirectionDatas.lien);
    $('#liste_redirection tbody #redirection_'+redirectionDatas.ligne_id+' td.code-redirection').html(redirectionDatas.code);
    var actionHtml = '<a class="pwe-ui-btn confirmAction right" title="Supprimer cette redirection" href="javascript:openRemoveRedirection('+redirectionDatas.ligne_id+',\''+redirectionDatas.lien+'\');">supprimer</a> <a class="pwe-ui-btn right" href="javascript:openUpdateRedirection('+redirectionDatas.ligne_id+',\''+redirectionDatas.lien+'\');">modifier</a>';
    $('#liste_redirection tbody #redirection_'+redirectionDatas.ligne_id+' td.action-redirection').html(actionHtml);
    $('.pwe-ui-btn').button();
    closeDialogBox();
    initConfirmAction();
};

// translate
var openTranslate = function(lang,modele,modele_id,propriete,input,editor){
    $('#dialogBox').dialog('option','title','Traduction : '+tableLangues[lang]);
    if(input=='input'){
        $('#dialogBox').dialog('option','width',450);
        $('#dialogBox').dialog('option','height',105);
    }else{
        $('#dialogBox').dialog('option','width',800);
        $('#dialogBox').dialog('option','height',510);
    }
    $('#dialogBox iframe').attr('src',baseUrl+'admin/tools/editTranslate.php?lang='+lang+'&modele='+modele+'&modele_id='+modele_id+'&propriete='+propriete+'&input='+input+'&editor='+editor);
    $('#dialogBox').dialog('open');
};


// tag
var openTag = function(action,publication_id,tag_id){
    if(action === 'update' || action === 'add' || action === 'create' ){
        $('#dialogBox').dialog('option','title','Editer les tag ');
    }
    if(action === 'delete'){
        $('#dialogBox').dialog('option','title','Supprimer le tag ');
    }
    
    $('#dialogBox').dialog('option','width',540);
    $('#dialogBox').dialog('option','height',205);
    $('#dialogBox iframe').attr('src','tools/editTag.php?action='+action+'&publication_id='+publication_id+'&tag_id='+tag_id);
    $('#dialogBox').dialog('open');
};

// fermer dialogue box
var closeDialogBox = function(reload){
    $('#dialogBox iframe').attr('src','');
    $('#dialogBox').dialog('close');
    if(reload) window.location.reload();
};

/* Ajax */

/* loader graphique */
var showAjaxLoader = function(){
    $('#ajax_loader').css('top',0);
};
var hideAjaxLoader = function(){
    $('#ajax_loader').css('top',-150);
};
var doAjax = function(target,data,callback,errorMsg,errorContainer){
    showAjaxLoader();
    $.ajax({
            type: "POST",
            url: target,
            data: data,
            dataType: 'json'
    })
    .always(function(){
        hideAjaxLoader();
    })
    .done(function(retour){
        if(retour.success){
            if(callback === 'reload') location.reload();
            else callback(retour.datas);
        }else{
            if(errorContainer!=='')$(errorContainer).html(errorMsg);
            else alert(errorMsg);
        }
    })
    .fail(function(jqXHR, textStatus){
        alert('Erreur de requête : ' + textStatus);
    });
};